#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <tokenhelper.h>

void usage()
{
    fprintf(stderr, "ytags_lua + filename\n");
    exit(1);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
        usage();

    const char *fn = argv[1];

    if (tk_open_file(fn) < 0) {
        fprintf(stderr, "open `%s' failed: %s\n", fn, strerror(errno));
        return 1;
    }

    int         lineno;
    std::string token;

    std::string obuf;

    obuf = "(change-file ";
    obuf += fn;
    obuf += ")\n";

    obuf.push_back('(');
    for (;;) {
        int type = tk_fetch_next(&lineno, token);

        if (type == TT_NONE)
            break;

        std::string elem;
        char lb[32];
        sprintf(lb, "%d", lineno);

        elem.push_back('(');
        elem += lb;
        elem.push_back(' ');
        elem += token;
        elem.push_back(' ');

        switch (type) {
        case TT_FUNC:
            elem += "function";
            break;

        case TT_REF:
            elem += "reference";
            break;
        }

        elem.push_back(')');
        obuf += elem;
    }
    obuf.push_back(')');

    fwrite(obuf.c_str(), 1, obuf.size(), stdout);
    fflush(stdout);

    tk_close_file();

    return 0;
}
